package com.hadluo.qq.client.utils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hadluo.qq.client.model.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class HttpClient {
    private static final String BASE_URL = "http://"+Constants.SERVER_HOST+":8080";
    private static final Gson gson = new Gson();

    public static LoginResponse login(String qqNumber, String password) throws IOException {
        LoginRequest loginRequest = new LoginRequest(qqNumber, password);
        String jsonRequest = gson.toJson(loginRequest);

        URL url = new URL(BASE_URL + "/api/user/login");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(10000);
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonRequest.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                JsonObject jsonResponse = gson.fromJson(response.toString(), JsonObject.class);
                boolean success = jsonResponse.has("success") && jsonResponse.get("success").getAsBoolean();
                String message = jsonResponse.has("message") ? jsonResponse.get("message").getAsString() : "";

                if (success && jsonResponse.has("data")) {
                    JsonObject data = jsonResponse.getAsJsonObject("data");
                    UserInfo userInfo = new UserInfo(
                            data.get("qqNumber").getAsString(),
                            data.get("nickname").getAsString()
                    );
                    if (data.has("avatar")) {
                        userInfo.setAvatar(data.get("avatar").getAsString());
                    }
                    if (data.has("signature")) {
                        userInfo.setSignature(data.get("signature").getAsString());
                    }
                    // 登录成功时保存登录信息
                    ConfigManager.saveLoginInfo(qqNumber, password);

                    return new LoginResponse(true, message, userInfo);
                }

                return new LoginResponse(false, message, null);
            }
        } else {
            return new LoginResponse(false, "服务器错误: " + responseCode);
        }
    }

    public static GroupMemberResponse getGroupMembers(Long groupId) throws IOException {
        URL url = new URL(BASE_URL + "/api/group/"+groupId+"/members");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setConnectTimeout(10000);

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }

                JsonObject jsonResponse = gson.fromJson(response.toString(), JsonObject.class);
                boolean success = jsonResponse.has("success") && jsonResponse.get("success").getAsBoolean();
                String message = jsonResponse.has("message") ? jsonResponse.get("message").getAsString() : "";

                if (success && jsonResponse.has("data")) {
                    JsonArray membersArray = jsonResponse.getAsJsonArray("data");
                    List<GroupMember> members = new ArrayList<>();

                    for (int i = 0; i < membersArray.size(); i++) {
                        JsonObject memberObj = membersArray.get(i).getAsJsonObject();
                        GroupMember member = new GroupMember();
                        if(memberObj.get("alias").isJsonNull()){
                            member.setNickname( memberObj.get("nickname").getAsString());
                        }else{
                            member.setNickname( memberObj.get("alias").getAsString());
                        }
                        if(!memberObj.get("avatar").isJsonNull()){
                            member.setAvatar(memberObj.get("avatar").getAsString());
                        }
                        if(!memberObj.get("role").isJsonNull()){
                            member.setRole(memberObj.get("role").getAsString());
                        }
                        members.add(member);
                    }

                    return new GroupMemberResponse(true, message, members);
                }

                return new GroupMemberResponse(false, message, null);
            }
        } else {
            return new GroupMemberResponse(false, "服务器错误: " + responseCode, null);
        }
    }


    public static GroupChatHistoryResponse getGroupChatHistory(String groupId) throws IOException {
        URL url = new URL(BASE_URL + "/api/group/history/"+groupId );
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setConnectTimeout(10000);

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }

                JsonObject jsonResponse = gson.fromJson(response.toString(), JsonObject.class);
                boolean success = jsonResponse.has("success") && jsonResponse.get("success").getAsBoolean();
                String message = jsonResponse.has("message") ? jsonResponse.get("message").getAsString() : "";

                if (success && jsonResponse.has("data")) {
                    JsonArray messagesArray = jsonResponse.getAsJsonArray("data");
                    List<GroupMessage> messages = new ArrayList<>();

                    for (int i = 0; i < messagesArray.size(); i++) {
                        JsonObject messageObj = messagesArray.get(i).getAsJsonObject();
                        GroupMessage chatMessage = new GroupMessage();
                        chatMessage.setSenderId(messageObj.get("senderId").getAsLong());
                        chatMessage.setContent(messageObj.get("content").getAsString());
                        chatMessage.setCreateTime(new Date(messageObj.get("timestamp").getAsLong()));
                        if (messageObj.has("type")) {
                            chatMessage.setType(messageObj.get("type").getAsString());
                        }
                        if (messageObj.has("user")) {
                            JsonObject user = messageObj.getAsJsonObject("user");
                            UserInfo userInfo = new UserInfo();

                            if (!user.get("signature").isJsonNull()) {
                                userInfo.setSignature(user.get("signature").getAsString());
                            }
                            if (!user.get("qqNumber").isJsonNull()) {
                                userInfo.setQqNumber(user.get("qqNumber").getAsString());
                            }
                            if (!user.get("nickname").isJsonNull()) {
                                userInfo.setNickname(user.get("nickname").getAsString());
                            }
                            if (!user.get("avatar").isJsonNull()) {
                                userInfo.setAvatar(user.get("avatar").getAsString());
                            }
                            if (!user.get("status").isJsonNull()) {
                                userInfo.setStatus(user.get("status").getAsString());
                            }
                            chatMessage.setUser(userInfo);
                        }

                        messages.add(chatMessage);
                    }

                    return new GroupChatHistoryResponse(true, message, messages);
                }

                return new GroupChatHistoryResponse(false, message);
            }
        } else {
            return new GroupChatHistoryResponse(false, "服务器错误: " + responseCode);
        }
    }

    public static boolean updateProfile(String qqNumber, String nickname, String avatar) throws IOException {
        JsonObject requestJson = new JsonObject();
        requestJson.addProperty("qqNumber", qqNumber);
        requestJson.addProperty("nickname", nickname);
        requestJson.addProperty("avatar", avatar);
        String jsonRequest = gson.toJson(requestJson);

        URL url = new URL(BASE_URL + "/api/user/update");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(10000);
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonRequest.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                JsonObject jsonResponse = gson.fromJson(response.toString(), JsonObject.class);
                return jsonResponse.has("success") && jsonResponse.get("success").getAsBoolean();
            }
        }
        return false;
    }

    public static UserInfoResponse getUserInfo(String qqNumber) throws IOException {
        URL url = new URL(BASE_URL + "/api/user/info?qqNumber=" + qqNumber);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setConnectTimeout(10000);

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }

                JsonObject jsonResponse = gson.fromJson(response.toString(), JsonObject.class);
                boolean success = jsonResponse.has("success") && jsonResponse.get("success").getAsBoolean();
                String message = jsonResponse.has("message") ? jsonResponse.get("message").getAsString() : "";

                if (success && jsonResponse.has("data")) {
                    JsonObject data = jsonResponse.getAsJsonObject("data");
                    UserInfo userInfo = new UserInfo(
                            data.get("qqNumber").getAsString(),
                            data.get("nickname").getAsString()
                    );
                    userInfo.setAvatar(data.get("avatar").getAsString());
                    userInfo.setSignature(data.get("signature").getAsString());
                    userInfo.setStatus(data.get("status").getAsString());

                    return new UserInfoResponse(true, message, userInfo);
                }

                return new UserInfoResponse(false, message);
            }
        }
        return new UserInfoResponse(false, "服务器错误: " + responseCode);
    }
}